package com.rbac.admin.controller.system;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.rbac.admin.annotation.OperationLog;
import com.rbac.admin.common.result.Result;
import com.rbac.admin.dto.system.UserDTO;
import com.rbac.admin.entity.system.SystemUser;
import com.rbac.admin.service.system.UserService;
import com.rbac.admin.vo.system.UserVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import jakarta.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 用户管理控制器
 *
 * @author rbac-admin
 * @since 2024-07-18
 */
@Tag(name = "用户管理", description = "用户管理相关接口")
@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 分页查询用户列表
     */
    @Operation(summary = "分页查询用户列表")
    @OperationLog(module = "用户管理", type = "查询", value = "查询用户列表")
    @GetMapping
    public Result<IPage<UserVO>> getUserList(
            @Parameter(description = "当前页") @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页大小") @RequestParam(defaultValue = "20") Integer size,
            @Parameter(description = "用户名") @RequestParam(required = false) String username,
            @Parameter(description = "昵称") @RequestParam(required = false) String nickname,
            @Parameter(description = "邮箱") @RequestParam(required = false) String email,
            @Parameter(description = "手机号") @RequestParam(required = false) String phone,
            @Parameter(description = "状态") @RequestParam(required = false) Integer status,
            @Parameter(description = "角色ID") @RequestParam(required = false) String roleId,
            @Parameter(description = "部门ID") @RequestParam(required = false) String deptId,
            @Parameter(description = "开始时间") @RequestParam(required = false) String startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) String endTime) {
        try {
            Page<UserVO> page = new Page<>(current, size);
            SystemUser queryUser = new SystemUser();

            queryUser.setUsername(username);
            queryUser.setNickname(nickname);
            queryUser.setEmail(email);
            queryUser.setPhone(phone);
            queryUser.setStatus(status);
            queryUser.setMainDeptId(deptId);

            IPage<UserVO> result = userService.getUserPage(page, queryUser);
            return Result.success(result);
        } catch (Exception e) {
            return Result.failed("获取用户列表失败：" + e.getMessage());
        }
    }

    /**
     * 根据ID获取用户详情
     */
    @Operation(summary = "根据ID获取用户详情")
    @OperationLog(module = "用户管理", type = "查询", value = "查看用户详情")
    @GetMapping("/{id}")
    public Result<UserVO> getUserById(@Parameter(description = "用户ID") @PathVariable String id) {
        try {
            UserVO user = userService.getUserById(id);
            if (user == null) {
                return Result.failed("用户不存在");
            }
            return Result.success(user);
        } catch (Exception e) {
            return Result.failed("获取用户详情失败：" + e.getMessage());
        }
    }

    /**
     * 创建用户
     */
    @Operation(summary = "创建用户")
    @OperationLog(module = "用户管理", type = "新增", value = "新增用户", recordParams = true, recordResult = true)
    @PostMapping
    public Result<UserVO> createUser(@RequestBody @Valid UserDTO userDTO) {
        try {
            // 检查用户名是否已存在
            SystemUser existUser = userService.getUserByUsername(userDTO.getUsername());
            if (existUser != null) {
                return Result.failed("用户名已存在");
            }

            UserVO user = userService.createUser(userDTO);
            return Result.success("用户创建成功", user);
        } catch (Exception e) {
            return Result.failed("用户创建失败：" + e.getMessage());
        }
    }

    /**
     * 更新用户
     */
    @Operation(summary = "更新用户")
    @OperationLog(module = "用户管理", type = "修改", value = "修改用户信息", recordParams = true, recordResult = true)
    @PutMapping("/{id}")
    public Result<UserVO> updateUser(
            @Parameter(description = "用户ID") @PathVariable String id,
            @RequestBody @Valid UserDTO userDTO) {
        try {
            // 检查用户是否存在
            SystemUser existUser = userService.getById(id);
            if (existUser == null) {
                return Result.failed("用户不存在");
            }

            // 如果修改了用户名，检查新用户名是否已被其他用户使用
            if (!existUser.getUsername().equals(userDTO.getUsername())) {
                SystemUser duplicateUser = userService.getUserByUsername(userDTO.getUsername());
                if (duplicateUser != null && !String.valueOf(duplicateUser.getId()).equals(id)) {
                    return Result.failed("用户名已被其他用户使用");
                }
            }
            UserVO user = userService.updateUser(id, userDTO);
            return Result.success("用户更新成功", user);
        } catch (Exception e) {
            return Result.failed("用户更新失败：" + e.getMessage());
        }
    }

    /**
     * 删除用户
     */
    @Operation(summary = "删除用户")
    @OperationLog(module = "用户管理", type = "删除", value = "删除用户", recordParams = true)
    @DeleteMapping("/{id}")
    public Result<String> deleteUser(@Parameter(description = "用户ID") @PathVariable String id) {
        try {
            // 检查用户是否存在
            SystemUser user = userService.getById(id);
            if (user == null) {
                return Result.failed("用户不存在");
            }

            boolean success = userService.deleteUser(id);
            if (success) {
                return Result.success("用户删除成功");
            } else {
                return Result.failed("用户删除失败");
            }
        } catch (Exception e) {
            return Result.failed("用户删除失败：" + e.getMessage());
        }
    }

    /**
     * 批量删除用户
     */
    @Operation(summary = "批量删除用户")
    @OperationLog(module = "用户管理", type = "删除", value = "批量删除用户", recordParams = true)
    @DeleteMapping("/batch")
    public Result<String> batchDeleteUsers(@RequestBody List<String> ids) {
        try {
            if (ids == null || ids.isEmpty()) {
                return Result.failed("请选择要删除的用户");
            }

            boolean success = userService.batchDeleteUsers(ids);
            if (success) {
                return Result.success("批量删除用户成功");
            } else {
                return Result.failed("批量删除用户失败");
            }
        } catch (Exception e) {
            return Result.failed("批量删除用户失败：" + e.getMessage());
        }
    }

    /**
     * 重置用户密码
     */
    @Operation(summary = "重置用户密码")
    @OperationLog(module = "用户管理", type = "修改", value = "重置用户密码", recordParams = false)
    @PutMapping("/{id}/password/reset")
    public Result<String> resetUserPassword(
            @Parameter(description = "用户ID") @PathVariable String id,
            @RequestBody(required = false) Map<String, String> params) {
        try {
            // 检查用户是否存在
            SystemUser user = userService.getById(id);
            if (user == null) {
                return Result.failed("用户不存在");
            }

            String newPassword = params != null ? params.get("newPassword") : "123456";
            boolean success = userService.resetPassword(id, newPassword);
            if (success) {
                return Result.success("密码重置成功");
            } else {
                return Result.failed("密码重置失败");
            }
        } catch (Exception e) {
            return Result.failed("密码重置失败：" + e.getMessage());
        }
    }

    /**
     * 修改用户状态
     */
    @Operation(summary = "修改用户状态")
    @OperationLog(module = "用户管理", type = "修改", value = "修改用户状态", recordParams = true)
    @PutMapping("/{id}/status")
    public Result<String> changeUserStatus(
            @Parameter(description = "用户ID") @PathVariable String id,
            @RequestBody Map<String, Integer> params) {
        try {
            // 检查用户是否存在
            SystemUser user = userService.getById(id);
            if (user == null) {
                return Result.failed("用户不存在");
            }

            Integer status = params.get("status");
            if (status == null) {
                return Result.failed("状态参数不能为空");
            }

            boolean success = userService.changeStatus(id, status);
            if (success) {
                return Result.success("状态修改成功");
            } else {
                return Result.failed("状态修改失败");
            }
        } catch (Exception e) {
            return Result.failed("状态修改失败：" + e.getMessage());
        }
    }

    /**
     * 获取用户角色列表
     */
    @Operation(summary = "获取用户角色列表")
    @GetMapping("/{id}/roles")
    public Result<List<String>> getUserRoles(@Parameter(description = "用户ID") @PathVariable String id) {
        try {
            // 检查用户是否存在
            SystemUser user = userService.getById(id);
            if (user == null) {
                return Result.failed("用户不存在");
            }

            List<String> roleIds = userService.getUserRoleIds(id);
            return Result.success(roleIds);
        } catch (Exception e) {
            return Result.failed("获取用户角色失败：" + e.getMessage());
        }
    }

    /**
     * 分配用户角色
     */
    @Operation(summary = "分配用户角色")
    @PutMapping("/{id}/roles")
    public Result<String> assignUserRoles(
            @Parameter(description = "用户ID") @PathVariable String id,
            @RequestBody Map<String, List<String>> params) {
        try {
            // 检查用户是否存在
            SystemUser user = userService.getById(id);
            if (user == null) {
                return Result.failed("用户不存在");
            }

            List<String> roleIds = params.get("roleIds");
            if (roleIds == null) {
                return Result.failed("角色ID列表不能为空");
            }

            boolean success = userService.assignRoles(id, roleIds);
            if (success) {
                return Result.success("角色分配成功");
            } else {
                return Result.failed("角色分配失败");
            }
        } catch (Exception e) {
            return Result.failed("角色分配失败：" + e.getMessage());
        }
    }

    /**
     * 导出用户数据
     */
    @Operation(summary = "导出用户数据")
    @GetMapping("/export")
    public Result<String> exportUserData(
            @Parameter(description = "用户名") @RequestParam(required = false) String username,
            @Parameter(description = "昵称") @RequestParam(required = false) String nickname,
            @Parameter(description = "状态") @RequestParam(required = false) Integer status) {
        try {
            SystemUser queryUser = new SystemUser();
            queryUser.setUsername(username);
            queryUser.setNickname(nickname);
            queryUser.setStatus(status);

            String filePath = userService.exportUserData(queryUser);
            return Result.success("导出成功", filePath);
        } catch (Exception e) {
            return Result.failed("导出用户数据失败：" + e.getMessage());
        }
    }

    /**
     * 导入用户数据
     */
    @Operation(summary = "导入用户数据")
    @PostMapping("/import")
    public Result<Map<String, Object>> importUserData(
            @Parameter(description = "导入文件") @RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return Result.failed("导入文件不能为空");
            }

            Map<String, Object> result = userService.importUserData(file);
            return Result.success("导入完成", result);
        } catch (Exception e) {
            return Result.failed("导入用户数据失败：" + e.getMessage());
        }
    }
} 